<?php
/**--------------------------------------------------------------------------+
 * Project:     CuteView: the PHP template engine                            |
 * File:        CuteViewStaticCacheEngine.php                                |
 *---------------------------------------------------------------------------+
 * This library is free software; you can redistribute it and/or             |
 * modify it under the terms of the GNU Lesser General Public                |
 * License as published by the Free Software Foundation; either              |
 * version 2.1 of the License, or (at your option) any later version.        |
 *                                                                           |
 * This library is distributed in the hope that it will be useful,           |
 * but WITHOUT ANY WARRANTY; without even the implied warranty of            |
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         |
 * Lesser General Public License for more details.                           |
 *                                                                           |
 * You should have received a copy of the GNU Lesser General Public          |
 * License along with this library; if not, write to the Free Software       |
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA |
 *                                                                           |
 * For questions, help, comments, discussion, etc., please contact the author|
 *---------------------------------------------------------------------------+
 * @copyright 2007-2007 blizzchris                                           |
 * @author Chris Yue <blizzchris@gmail.com>                                  |
 * @package CuteView                                                         |
 * @version 1.071222 beta                                                    |
 *---------------------------------------------------------------------------+
 */

require_once('Base/CuteViewEngine.php');

class CuteViewStaticCacheEngine extends CuteViewEngine 
{
	public  $update_interval = 3600;
	
	/**
	 * set true to always delete generated html file
	 * it is useful when designers attempt to change the template file
	 *
	 * @var bool
	 */
	public $always_delete_cache = false;
	
	
	/**---------------------+
	 * private members below|
	 *----------------------*/
	/**
	 * where the generated html files are put in
	 *
	 * @var string
	 */
	private $cache_file_root = 'compiled';
	
	/**
	 * the generated html file's path
	 *
	 * @var string
	 */
	private $cache_file_path;
	
	/**
	 * whether need to update the old html file this time
	 *
	 * @var bool
	 */
	private $need_update = false;
	
	
	
	/**
	 * set where to put the generate html files in
	 *
	 * @param string $root_path
	 */
	public function setCacheRootPath($root_path)
	{
		$this -> cache_file_root = rtrim($root_path) . "/";
	}
	
	public function needUpdate()
	{
		if ( $this -> always_delete_cache )
		{
			$this -> need_update = true;
			return true;
		}
		
		if ( !$this -> cacheFileExists() )
		{
			$this -> need_update = true;
			return true;
		}
		
		if ( $this -> update_interval == 0 ) 
		{
			$this -> need_update = false;
			return false;
		}
		
		$this -> loadCacheFile();
		$ts_create = $this -> getCacheFileCreateTs();
		$ts_now = time();
		
		if ( $ts_now - $ts_create < $this -> update_interval )
		{
			$this -> need_update = false;
		}
		else 
		{
			$this -> need_update = true;
		}
		return $this -> need_update;
	}
	
	public function display()
	{
		if ( $this -> need_update )
		{
			if ( $this -> cacheFileExists() )
			{
				$this -> deleteCacheFile();
			}
			$this -> handleTemplate();
			$this -> generateCacheFile();
		}
		$this -> output();
	}
	
	private function cacheFileExists()
	{
		$this -> cache_file_path = str_replace("/", "_", $this -> file_path) . ".html";
		if ( file_exists("{$this -> cache_file_root}{$this -> cache_file_path}") )
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	/**
	 * get generated file's create timestamp
	 *
	 * @return int timestamp
	 */
	private function getCacheFileCreateTs()
	{
		$pattern = "|<!-- Generated by CuteView on (.*) -->|U";
		preg_match($pattern, $this -> content, $out);
		$datetime_create = $out[1];
		return strtotime($datetime_create);
	}
	
	private function loadCacheFile()
	{
		$this -> content = file_get_contents("{$this -> cache_file_root}{$this -> cache_file_path}");
	}
	
	private function deleteCacheFile()
	{
		@unlink("{$this -> cache_file_root}{$this -> cache_file_path}")
			or die("Delete cache file {$this -> cache_file_path} failed");
	}
	
	private function generateCacheFile()
	{
		ob_start();
		$this -> execute();
		$content = ob_get_contents();
		ob_end_clean();
		$time_create = date("Y-m-d H:i:s");
		$this -> content = "<!-- Generated by CuteView on $time_create -->\n{$content}";
		file_put_contents("{$this -> cache_file_root}{$this -> cache_file_path}", $this -> content);
	}
	
	/**
	 * output generated html file content
	 *
	 */
	private function output()
	{
		if ( empty($this -> content) ) 
		{
			die("<em>CuteView:\"needUpdate\" method needed</em>");
		}
		echo $this -> content;
	}
	
}